package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import com.google.gson.reflect.TypeToken
import com.sy.simpleegg.R
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.bean.CashGoodBean
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.databinding.FragmentPackageManageBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.PackageManageContract
import com.sy.simpleegg.mvp.presenter.PackageManagePresenter
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.SPHelper
import com.sy.logger.Logger

class PackageManageFragment :
    BaseMvpFragment<PackageManageContract.View, PackageManageContract.Presenter, FragmentPackageManageBinding>(),
    PackageManageContract.View {

    companion object {
        fun getInstance(): PackageManageFragment = PackageManageFragment()
    }

    override fun createPresenter(): PackageManageContract.Presenter = PackageManagePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_package_manage

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = false
        isCountDownBackHome = false
    }

    override fun initView(view: View) {
        super.initView(view)

        binding.tvBillSymboles0.text = Config.CURRENCY_SYMBOLS
        binding.tvBillSymboles1.text = Config.CURRENCY_SYMBOLS
        binding.tvBillSymboles2.text = Config.CURRENCY_SYMBOLS
        binding.tvBillSymboles3.text = Config.CURRENCY_SYMBOLS
        binding.tvBillSymboles4.text = Config.CURRENCY_SYMBOLS
        binding.tvBillSymboles5.text = Config.CURRENCY_SYMBOLS

        binding.tvCoinSymboles0.text = Config.CURRENCY_SYMBOLS
        binding.tvCoinSymboles1.text = Config.CURRENCY_SYMBOLS
        binding.tvCoinSymboles2.text = Config.CURRENCY_SYMBOLS
        binding.tvCoinSymboles3.text = Config.CURRENCY_SYMBOLS
        binding.tvCoinSymboles4.text = Config.CURRENCY_SYMBOLS
        binding.tvCoinSymboles5.text = Config.CURRENCY_SYMBOLS

        binding.btnSavePackage.setOnClickListener {
            if (!isFirstClick()){
                return@setOnClickListener
            }
            saveCashPackage()
        }

        setData()

//        binding.rlTouch.setTouchListener(object : TouchRelativeLayout.TouchListener {
//            override fun touch() {
//                startCountDown()
//            }
//        })
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentPackageManageBinding {
        return FragmentPackageManageBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    /**
     * 配置数据
     */
    private fun setData() {
        try {
            var cashPackageList: MutableList<CashGoodBean> = mutableListOf()
            val cashPackage: String = SPHelper.getCashPackage()
            if (cashPackage.isNotEmpty()) {
                cashPackageList = GsonUtil.getInstance()
                    ?.fromJson(cashPackage, object : TypeToken<MutableList<CashGoodBean>>() {}.type)!!
            } else {
                val bean0 = CashGoodBean("5", "100", "1", "0", 5)
                val bean1 = CashGoodBean("4", "500", "5", "0", 4)
                val bean2 = CashGoodBean("3", "1000", "10", "0", 3)
                val bean3 = CashGoodBean("2", "2000", "20", "0", 2)
                val bean4 = CashGoodBean("1", "5000", "60", "0", 1)
                val bean5 = CashGoodBean("0", "10000", "140", "0", 0)
                cashPackageList.add(bean5)
                cashPackageList.add(bean4)
                cashPackageList.add(bean3)
                cashPackageList.add(bean2)
                cashPackageList.add(bean1)
                cashPackageList.add(bean0)
            }
            if (cashPackageList.size > 0) {
                for (cashGoodBean in cashPackageList) {
                    when (cashGoodBean.sort) {
                        0 -> showData(cashGoodBean, binding.etPackageAmount0, binding.etPackageCoin0, binding.etPackageDonate0)
                        1 -> showData(cashGoodBean, binding.etPackageAmount1, binding.etPackageCoin1, binding.etPackageDonate1)
                        2 -> showData(cashGoodBean, binding.etPackageAmount2, binding.etPackageCoin2, binding.etPackageDonate2)
                        3 -> showData(cashGoodBean, binding.etPackageAmount3, binding.etPackageCoin3, binding.etPackageDonate3)
                        4 -> showData(cashGoodBean, binding.etPackageAmount4, binding.etPackageCoin4, binding.etPackageDonate4)
                        5 -> {
                            val coin: String = cashGoodBean.value
                            binding.etPackageCoin5.setText(coin)
                        }

                        else -> {}
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("配置纸钞套餐数据异常：" + e.message)
        }
    }

    private fun showData(
        cashGoodBean: CashGoodBean,
        etAmount: EditText,
        etCoin: EditText,
        etAdd: EditText
    ) {
        try {
            etAmount.setText((cashGoodBean.price.toInt() / 100).toString())
            etCoin.setText(cashGoodBean.value)
            etAdd.setText(cashGoodBean.flag)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("纸钞套餐数据：" + GsonUtil.getInstance()?.toJson(cashGoodBean))
            logFile("显示纸钞套餐数据异常：" + e.message)
        }
    }

    private fun checkData(etAmount: EditText?, etCoin: EditText?, etAdd: EditText?): Boolean {
        return try {
            if (etAmount != null && etCoin != null && etAdd != null) {
                val amountStr = etAmount.text.toString()
                val coinStr = etCoin.text.toString()
                val addStr = etAdd.text.toString()
                if (amountStr.length == 0 && coinStr.length == 0 && addStr.length == 0) {
                    true
                } else {
                    if (amountStr == "0" || coinStr == "0") {
                        showToastMsg(getString(R.string.no_zero))
                        false
                    } else {
                        val amount = amountStr.toInt()
                        val coin = coinStr.toInt()
                        if (amount == 0 || coin == 0) {
                            false
                        } else true
                    }
                }
            } else {
                false
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("校验纸钞套餐数据异常：" + e.message)
            false
        }
    }

    /**
     * 保存现金套餐数据
     */
    private fun saveCashPackage(){
        try {
            var count = 0
            if (checkData(
                    binding.etPackageAmount0,
                    binding.etPackageCoin0,
                    binding.etPackageDonate0
                )
            ) {
                count++
            } else {
                showToastMsg("套餐1数据不正确")
            }
            if (checkData(
                    binding.etPackageAmount1,
                    binding.etPackageCoin1,
                    binding.etPackageDonate1
                )
            ) {
                count++
            } else {
                showToastMsg("套餐2数据不正确")
            }
            if (checkData(
                    binding.etPackageAmount2,
                    binding.etPackageCoin2,
                    binding.etPackageDonate2
                )
            ) {
                count++
            } else {
                showToastMsg("套餐3数据不正确")
            }
            if (checkData(
                    binding.etPackageAmount3,
                    binding.etPackageCoin3,
                    binding.etPackageDonate3
                )
            ) {
                count++
            } else {
                showToastMsg("套餐4数据不正确")
            }
            if (checkData(
                    binding.etPackageAmount4,
                    binding.etPackageCoin4,
                    binding.etPackageDonate4
                )
            ) {
                count++
            } else {
                showToastMsg("套餐5数据不正确")
            }
            val coin5Str: String = binding.etPackageCoin5.text.toString()
            if (coin5Str.length > 0) {
                val coin = coin5Str.toInt()
                if (coin > 0) {
                    count++
                } else {
                    showToastMsg("套餐6数据要大于0")
                }
            } else {
                showToastMsg("套餐6数据不能为空")
            }
            if (count == 6) {
                saveData()
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("保存现金套餐数据异常：${e.message}")
        }
    }

    private fun saveData() {
        try {
            val cashGoodBean0 = makeData(0, binding.etPackageAmount0, binding.etPackageCoin0, binding.etPackageDonate0)
            val cashGoodBean1 = makeData(1, binding.etPackageAmount1, binding.etPackageCoin1, binding.etPackageDonate1)
            val cashGoodBean2 = makeData(2, binding.etPackageAmount2, binding.etPackageCoin2, binding.etPackageDonate2)
            val cashGoodBean3 = makeData(3, binding.etPackageAmount3, binding.etPackageCoin3, binding.etPackageDonate3)
            val cashGoodBean4 = makeData(4, binding.etPackageAmount4, binding.etPackageCoin4, binding.etPackageDonate4)
            val coin5Str = binding.etPackageCoin5.text.toString()
            var coin5 = 1
            if (coin5Str.isNotEmpty()) {
                val coin = coin5Str.toInt()
                if (coin > 0) {
                    coin5 = coin
                }
            }
            val cashGoodBean5 = CashGoodBean("5", "100", coin5.toString(), "0", 5)
            val cashGoodBeanList: MutableList<CashGoodBean> = ArrayList()
            if (cashGoodBean0 != null) {
                cashGoodBeanList.add(cashGoodBean0)
            }
            if (cashGoodBean1 != null) {
                cashGoodBeanList.add(cashGoodBean1)
            }
            if (cashGoodBean2 != null) {
                cashGoodBeanList.add(cashGoodBean2)
            }
            if (cashGoodBean3 != null) {
                cashGoodBeanList.add(cashGoodBean3)
            }
            if (cashGoodBean4 != null) {
                cashGoodBeanList.add(cashGoodBean4)
            }
            if (cashGoodBean5 != null) {
                cashGoodBeanList.add(cashGoodBean5)
            }
            val cashPackage = GsonUtil.getInstance()!!.toJson(cashGoodBeanList)
            logFile("纸币套餐数据：$cashPackage")
            SPHelper.setCashPackage(cashPackage)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            logFile("保存纸钞套餐数据异常2：" + e.message)
        }
    }

    private fun makeData(
        sort: Int,
        etAmount: EditText,
        etCoin: EditText,
        etAdd: EditText
    ): CashGoodBean? {
        return try {
            val amountStr = etAmount.text.toString()
            val coinStr = etCoin.text.toString()
            var addStr = etAdd.text.toString()
            val amount = amountStr.toInt()
            val coin = coinStr.toInt()
            if (addStr.length == 0) {
                addStr = "0"
            }
            val add = addStr.toInt()
            CashGoodBean(
                sort.toString(),
                (amount * 100).toString(),
                coin.toString(),
                add.toString(),
                sort
            )
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Logger.e("构建纸币套餐数据异常：" + e.message)
            null
        }
    }
}